<template>
  <div>
    <el-form
      :model="form"
      ref="form"
      label-width="144px"
      class="ccui-form"
      :rules="rules"
    >
      <el-row :gutter="10">
        <el-col :span="18">
          <el-form-item label="变更原因：" prop="changeReason">
            <el-input
              type="textarea"
              :rows="5"
              maxlength="300"
              show-word-limit
              placeholder="请输入变更原因"
              v-model="form.changeReason"
            >
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="填报单位：" prop="reportInOrgId">
            <el-input v-model="form.reportInOrgName" disabled />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="合同签订单位(甲方)：" prop="partyAName">
            <el-input v-model="form.partyAName" disabled />
          </el-form-item>
        </el-col>
      </el-row>

      <!--项目名称、争议解决方案-->
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="项目名称：" prop="projectName">
            <el-input v-model="form.projectName" disabled />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="争议解决方案：" prop="disputeResolutionCode">
            <el-select
              v-model="form.disputeResolutionName"
              placeholder="请选择争议解决方案"
              @change="changeDisputeResolutionCode(form.disputeResolutionName)"
            >
              <el-option
                v-for="item in disputeResolutionOptions"
                :key="item.code"
                :label="item.name"
                :value="item.name"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="供应商1：" prop="partyBName">
            <el-input v-model="form.partyBName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供应商2：" prop="partyBNameBak">
            <el-input v-model="form.partyBNameBak" disabled />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="合同编号：" prop="contractCode">
            <el-input v-model="form.contractCode" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同名称：" prop="contractName">
            <el-input
              v-model="form.contractName"
              maxlength="300"
              placeholder="请输入合同名称"
              @blur="handleTrim('contractName')"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="协议编号：" prop="protocalCode">
            <el-input v-model="form.protocalCode" disabled />
            <!-- 协议编号 -->
            <template v-if="optionalProtocal">
              <dialogMultiSelectTable
                dialogTitle="框架协议参照选择"
                isShow
                selectableNode="protocalCode"
                :searchInputArr="baseJsObj.agreementSearchInputArr"
                :tableHeadOptions="baseJsObj.agreementTableHeadOptions"
                :getTableList="listProtocolinfoPage"
                :optionalParams="optionalParams"
                :selectTableList="[]"
                @confirm="confirmSelect"
              />
              <el-button
                plain
                type="single-number"
                style="margin-left: 10px"
                @click="handleProtocalCode"
                >清空</el-button
              >
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否海外采购：" prop="isOverseas">
            <el-select
              v-model="form.isOverseas"
              placeholder="请选择"
              :disabled="!!form.protocalCode"
              @change="isOverseasChange"
            >
              <el-option
                v-for="item in baseJsObj.isOverseasList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :disabled="item.value === -1"
              >
                <span v-if="item.isLeaf" :class="{ optionLeaf: item.isLeaf }"
                  >├ {{ item.label }}</span
                >
                <span v-else>{{ item.label }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item
            v-if="
              form.isOverseas !== 3 &&
                !['人民币', '美元'].includes(form.currencyName)
            "
            label="兑美元汇率："
            prop="usExchangeRate"
            key="usExchangeRate"
          >
            <el-input
              v-model="form.usExchangeRate"
              placeholder="请输入兑美元汇率"
              maxlength="30"
              @blur="handleCurrencyChange('usExchangeRate')"
            />
          </el-form-item>
          <el-form-item v-else />
        </el-col>

        <el-col :span="12">
          <el-form-item label="币种：" prop="currencyName">
            <el-select
              v-model="form.currencyName"
              placeholder="请选择币种"
              :disabled="!!form.protocalCode"
              filterable
              @change="handleChange('currency')"
            >
              <el-option
                v-for="item in Enum.currencyList"
                :key="item.dicKey"
                :label="item.dicValue"
                :value="item.dicValue"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- <el-row :gutter="10" v-if="!['人民币'].includes(form.currencyName)">
        <el-col :span="12">
          <el-form-item
            label="兑人民币汇率："
            prop="chExchangeRate"
            key="chExchangeRate"
          >
            <el-input
              v-model="form.chExchangeRate"
              placeholder="请输入兑人民币汇率"
              maxlength="30"
              @blur="handleCurrencyChange('chExchangeRate')"
            />
          </el-form-item>
        </el-col>
      </el-row> -->

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item
            label="兑人民币汇率："
            prop="chExchangeRate"
            key="chExchangeRate"
          >
            <el-input
              v-model="form.chExchangeRate"
              placeholder="请输入兑人民币汇率"
              maxlength="30"
              @blur="handleCurrencyChange('chExchangeRate')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="汇率参照日期：" prop="exchangeRateRefDate">
            <!-- <el-input v-model="form.exchangeRateRefDate" disabled /> -->
            <div class="block">
              <!-- <span class="demonstration">默认</span> -->
              <el-date-picker
                v-model="form.exchangeRateRefDate"
                type="date"
                placeholder="选择日期"
              >
              </el-date-picker>
            </div>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item
            label="合同金额(含税)"
            prop="initTotalContractPriceIncludeTax"
          >
            <el-input
              v-model="form.initTotalContractPriceIncludeTax"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="合同金额(不含税)："
            prop="initTotalConractPriceExcludeTax"
          >
            <el-input v-model="form.initTotalConractPriceExcludeTax" disabled />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="是否浮动价格：" prop="isFloatContractPrice">
            <el-radio-group v-model="form.isFloatContractPrice">
              <el-radio
                v-for="item in baseJsObj.whetherList"
                :key="item.dicKey"
                :label="item.dicKey"
                >{{ item.dicValue }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="编制人：" prop="compileUser">{{
            form.compileUser
          }}</el-form-item>
        </el-col>
      </el-row>

      <!--发票类型、合同范本使用情况-->
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="发票类型：" prop="invoiceCode">
            <el-select
              v-model="form.invoiceName"
              placeholder="请选择发票类型"
              @change="changeInvoiceCode(form.invoiceName)"
            >
              <el-option
                v-for="item in Enum.invoiceList"
                :key="item.dicKey"
                :label="item.dicValue"
                :value="item.dicValue"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item
            label="合同范本使用情况："
            prop="useOfModelContractCode"
          >
            <el-select
              v-model="form.useOfModelContractName"
              placeholder="请选择合同范本使用情况"
              @change="
                changeUseOfModelContractCode(form.useOfModelContractName)
              "
            >
              <el-option
                v-for="item in useOfModelContractOptions"
                :key="item.code"
                :label="item.name"
                :value="item.name"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="多税率：" prop="multiRateCode">
            <el-radio-group
              v-model="form.multiRateCode"
              @change="multiRateCodeChange"
            >
              <el-radio
                v-for="item in baseJsObj.whetherList"
                :key="item.dicKey"
                :label="item.dicKey"
                >{{ item.dicValue }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            v-if="form.multiRateCode === 1"
            label="税率："
            prop="taxRatePercent"
            key="taxRatePercent"
          >
            <el-select
              v-model="form.taxRatePercent"
              placeholder="请选择税率"
              @change="handleChange('taxRatePercent')"
            >
              <el-option
                v-for="item in Enum.taxRateCodeList"
                :key="item.dicKey"
                :label="item.dicValue"
                :value="item.dicValue"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-else />
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="对方联系人：" prop="contractPerson">
            <el-input
              v-model="form.contractPerson"
              placeholder="请输入对方联系人"
              maxlength="20"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="物资来源：" prop="transportCategoryCode">
            <el-select
              v-model="form.transportCategoryCode"
              placeholder="请选择物资来源"
              filterable
              @change="handleChange('transportCategoryCode')"
            >
              <el-option
                v-for="item in baseJsObj.transportCategory"
                :key="item.dicKey"
                :label="item.dicValue"
                :value="item.dicKey"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item
            label="对方联系手机号："
            :prop="
              form.isOverseas === 3
                ? 'contractPersonTel'
                : 'contractPersonTelOverSea'
            "
          >
            <el-input
              v-model="form.contractPersonTel"
              maxlength="15"
              placeholder="请输入对方联系手机号"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="编制日期：" prop="compileDate">
            <!-- <el-date-picker
              v-model="form.compileDate"
              type="date"
              placeholder="请选择编制日期"
              value-format="yyyy-MM-dd"
              :clearable="false"
              disabled
            /> -->
            <el-input v-model="form.compileDate" disabled />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10" v-if="form.isFloatContractPrice === 0">
        <el-col :span="18">
          <el-form-item label="浮动价说明：" prop="floatDesc">
            <el-input
              type="textarea"
              :rows="5"
              maxlength="500"
              show-word-limit
              placeholder="请输入浮动价说明"
              v-model="form.floatDesc"
            >
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="18">
          <el-form-item label="合同主要条款：" prop="mainTermsOfContract">
            <el-input
              type="textarea"
              :rows="5"
              maxlength="500"
              show-word-limit
              placeholder="请输入合同主要条款"
              v-model="form.mainTermsOfContract"
            >
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="18">
          <el-form-item label="备注：" prop="remark">
            <el-input
              type="textarea"
              :rows="5"
              maxlength="500"
              show-word-limit
              placeholder="请输入备注"
              v-model="form.remark"
            >
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { mapActions, mapGetters } from "vuex";
import { dateFormat1, proxyDateFormat } from "@/basa/utils";
import { listProtocolinfoPage } from "../api";
import { getUserInfoA, postGetEnum } from "@/basa/api";
import validators from "@/basa/utils/validators";
import jsObj from "../js";
import baseJsObj from "@/app/contractManagement/materialRentContract/contractDraft/js";
import dialogMultiSelectTable from "@/basa/components/public/dialogMultiSelectTable";
export default {
  name: "baseInfo",
  props: {
    detail: {
      type: Object,
      default: () => {}
    }
  },
  components: { dialogMultiSelectTable },
  data() {
    return {
      // jsList,
      jsObj,
      baseJsObj,
      Enum: {
        currencyList: [], // 币种
        taxRateCodeList: [], // 税率
        materialSourceList: [], // 物资来源
        invoiceList: [] // 发票
      },
      smpProjectReqBO: {},
      form: {
        reportInOrgId: "", // 填报单位
        reportInOrgName: "", // 填报单位
        projectCode: "", // 项目名称编码
        projectName: "", // 项目名称
        disputeResolutionCode: "", //争议解决方式编码
        disputeResolutionName: "", //争议解决方式名称
        invoiceCode: "", // 发票类型编码
        invoiceName: "", // 发票类型名称
        useOfModelContractCode: "", // 合同范本编码
        useOfModelContractName: "", // 合同范本名称
        partyAName: "", // 合同签订单位(甲方)
        partyAId: " ", // 合同签订单位id
        partyBName: "", // 供应商1
        partyBNameBak: "", // 供应商2
        contractCode: "", // 合同编号
        contractName: "", // 合同名称
        protocalCode: "", // 协议编号
        protocalId: "", // 协议编号
        protocalName: "", // 协议编号
        currencyName: "人民币", // 币种
        currencyCode: "1", // 币种
        chExchangeRate: "", // 兑人民币汇率
        exchangeRateRefDate: "", // 汇率参照日期
        initTotalContractPriceIncludeTax: "", // 合同金额(含税)元
        initTotalConractPriceExcludeTax: "", // 合同金额(不含税)元
        isFloatContractPrice: 0, // 是否浮动合同价格
        isOverseas: "", // 是否海外采购
        taxRateCode: "", // 税率
        multiRateCode: 1, // 多税率
        contractPerson: "", // 对方联系人
        transportCategoryCode: "01", // 运输产品类别
        transportCategoryName: "钢材", // 运输产品类别
        contractPersonTel: "", // 对方联系手机号
        compileDate: "", // 编制日期
        compileUser: "", // 编制人
        usExchangeRate: "", // 兑美元汇率
        floatDesc: "", // 浮动价说明
        mainTermsOfContract: "", // 合同主要条款
        remark: "", // 备注
        isShow: 0
      },
      rules: {
        changeReason: [
          { required: true, message: "请输入变更原因", trigger: "blur" }
        ],
        reportInOrgId: [
          { required: true, message: "请输入填报单位", trigger: "blur" }
        ],
        partyAName: [
          {
            required: true,
            message: "请输入合同签订单位(甲方)",
            trigger: "blur"
          }
        ],
        projectName: [
          { required: true, message: "请选择项目名称", trigger: "change" }
        ],
        disputeResolutionCode: [
          { required: true, message: "请选择争议解决方案", trigger: "blur" }
        ],
        partyBName: [
          { required: true, message: "请选择供应商1", trigger: "change" }
        ],
        taxRatePercent: [
          { required: true, message: "请选择税率", trigger: "change" }
        ],
        contractName: [
          { required: true, message: "请输入合同名称", trigger: "blur" }
        ],
        currencyName: [
          { required: true, message: "请选择币种", trigger: "change" }
        ],
        chExchangeRate: [
          { required: true, message: "请输入兑人民币汇率", trigger: "blur" },
          {
            pattern: /(^(\d{0,21})\.(\d{0,4})$)|(^\d{0,26}$)/,
            message: "请输入正确的税率",
            trigger: "blur"
          }
        ],
        isFloatContractPrice: [
          {
            required: true,
            message: "请选择是否浮动合同价格",
            trigger: "change"
          }
        ],
        isOverseas: [
          { required: true, message: "请选择是否海外运输", trigger: "change" }
        ],
        taxRateCode: [
          { required: true, message: "请选择税率", trigger: "change" }
        ],
        invoiceCode: [
          { required: true, message: "请选择发票类型", trigger: "blur" }
        ],
        useOfModelContractCode: [
          {
            required: true,
            message: "请选择合同范本使用情况",
            trigger: "blur"
          }
        ],
        multiRateCode: [
          { required: true, message: "请输入多税率", trigger: "blur" }
        ],
        contractPerson: [
          { required: true, message: "请输入对方联系人", trigger: "blur" }
        ],
        transportCategoryCode: [
          { required: true, message: "请选择运输产品类别", trigger: "change" }
        ],
        contractPersonTel: [
          {
            required: true,
            message: "请输入对方联系手机号",
            trigger: "blur"
          },
          {
            validator: validators.userMobile,
            message: "请输入正确的手机号",
            trigger: "blur"
          }
        ],
        contractPersonTelOverSea: [
          {
            max: 15,
            trigger: "blur"
          }
        ],
        floatDesc: [
          { required: true, message: "请输入浮动价说明", trigger: "blur" }
        ],
        usExchangeRate: [
          { required: true, message: "请输入兑美元汇率", trigger: "blur" },
          {
            pattern: /(^(\d{0,21})\.(\d{0,4})$)|(^\d{0,26}$)/,
            message: "请输入正确的税率",
            trigger: "blur"
          }
        ],
        compileUser: [
          {
            required: true,
            trigger: "blur"
          }
        ],
        compileDate: [
          {
            required: true,
            trigger: "blur"
          }
        ]
      },
      invoiceOptions: [], // 发票类型
      disputeResolutionOptions: [
        { code: "01", name: "诉讼" },
        { code: "02", name: "仲裁" },
        { code: "03", name: "内部调解" },
        { code: "04", name: "协商" },
        { code: "99", name: "其他" }
      ], // 争议解决方案
      useOfModelContractOptions: [
        { code: "01", name: "使用国家、行业范本" },
        { code: "02", name: "使用本单位范本" },
        { code: "03", name: "使用对方范本" },
        { code: "99", name: "未使用范本" }
      ], // 合同范本使用情况
      userOpenId: "",
      afterVal: 0,
      optionalParams: {},
      agreementSelectTableList: [],
      initIsOverseas: null,
      initCurrencyCode: null,
      initCurrencyName: null,
      initProtocalCode: null,
      initProtocalId: null,
      initProtocalName: null,
      beforeIsOverseas: "",
      beforeCurrencyCode: "",
      beforeCurrencyName: "",
      beforeProtocalCode: "",
      beforeProtocalId: "",
      beforeProtocalName: "",
      optionalProtocal: false
    };
  },
  created() {
    this.init();

    this.$bus.$on(
      "setPriceSum",
      ({ setContractPriceIncludeTax, setContractPriceExcludeTax }) => {
        this.form.initTotalContractPriceIncludeTax = Number(
          setContractPriceIncludeTax
        ).toFixed(2);
        this.form.initTotalConractPriceExcludeTax = Number(
          setContractPriceExcludeTax
        ).toFixed(2);
      }
    );

    this.$once("hook:beforeDestroy", () => {
      this.$bus.$off("setPriceSum");
    });
  },
  methods: {
    init() {
      this.setShowDoubleTable(false);
      this.getUserInfo();
      this.postGetEnum();
      const { smpPcConc, pcFinance } = this.detail;
      this.form = {
        ...smpPcConc,
        compileDate: dateFormat1(new Date()),
        chExchangeRate: smpPcConc.chExchangeRate
          ? Number(smpPcConc.chExchangeRate).toFixed(4)
          : "",
        usExchangeRate: smpPcConc.usExchangeRate
          ? Number(smpPcConc.usExchangeRate).toFixed(4)
          : "",
        exchangeRateRefDate: smpPcConc.exchangeRateRefDate
          ? proxyDateFormat(smpPcConc.exchangeRateRefDate)
          : "",
        signDate: smpPcConc.signDate ? proxyDateFormat(smpPcConc.signDate) : "",
        createTime: smpPcConc.createTime
          ? proxyDateFormat(smpPcConc.createTime)
          : "",
        materialSource: pcFinance?.materialSource
          ? String(pcFinance?.materialSource)
          : "自购",
        materialSourceCode: pcFinance?.materialSourceCode || "",
        contractPerson: pcFinance.length ? pcFinance[0].contractPerson : "",
        contractPersonTel: pcFinance.length
          ? pcFinance[0].contractPersonTel
          : "",
        multiRateCode: this.detail.smpPcConc.multiRateCode ?? 1
      };
      this.optionalParams = {
        ...this.optionalParams,
        reportInOrgId: this.detail.smpPcConc.reportInOrgId,
        supCode: this.form.partyBId || ""
      };

      // 框架协议是否可选择
      this.optionalProtocal = this.detail.isDisplaySup === "0";
    },

    // 获取枚举
    postGetEnum() {
      const arr = [
        "getCurrencyTypeDict", // 查询币种字典数据
        "getTaxRateDict", // 查询税率字典数据
        "getSourcesDict", // 查询物资来源字典数据
        "getReceiptTypeDict" // 查询发票类型
      ];
      for (let i = 0; i < arr.length; i++) {
        const element = arr[i];
        postGetEnum(element).then(res => {
          this.Enum[Object.keys(this.Enum)[i]] = res.data.data;
        });
      }
    },
    // 取消协议编码
    handleProtocalCode() {
      this.form.protocalCode = "";
      this.form.protocalId = "";
      this.form.protocalName = "";

      // 清空清单的协议
      this.setDelectList(true);

      // 设置清单列表中的采购计划选择状态
      this.setAgreementSelectStatus(false);
    },

    handleChange(type) {
      // if (this.form.protocalCode && type === "currency") {
      //   this.form.currencyName = this.beforeCurrencyName;
      //   return this.$showErrorMessage("已经引用协议编号，不允许改变币种");
      // }

      let val = this.form[type === "currency" ? `${type}Name` : type];

      // 处理税率
      if (type === "taxRatePercent") {
        const obj = this.Enum.taxRateCodeList.find(_ => _.dicValue === val);
        this.form.taxRateCode = obj.dicKey;
        if (val !== "免税") {
          const newVal = val.match(/\d+(.\d+)?/g)[0];
          this.form.taxRate = newVal;
          this.afterVal = Number(newVal) / 100;
        } else {
          this.form.taxRate = Number(obj.dicKey);
          this.afterVal = Number(obj.dicKey);
        }
        this.setTaxRate(this.afterVal);
        this.setTaxRateObj(obj);
      } else if (type === "transportCategoryCode") {
        this.form.transportCategoryName = baseJsObj.transportCategory.find(
          _ => _.dicKey === val
        ).dicValue;
      } else {
        this.form[`${type}Code`] = this.Enum[`${type}List`].find(
          _ => _.dicValue === val
        ).dicKey;
      }

      this.$refs["form"].clearValidate(["chExchangeRate"]);

      if (type === "currency") {
        this.setCurrencyObj({
          code: this.form[`${type}Code`],
          name: val
        });
      }
    },

    getUserInfo() {
      getUserInfoA().then(res => {
        this.form.compileUser = this.detail.smpPcConc.compileUser;
        this.userOpenId = res.data.data.userInfo.openId;
      });
    },

    // 争议解决方案
    changeDisputeResolutionCode(name) {
      this.form.disputeResolutionCode = this.disputeResolutionOptions.find(
        _ => _.name === name
      ).code;
    },

    // 发票类型
    changeInvoiceCode(val) {
      this.form.invoiceCode = this.Enum.invoiceList.find(
        _ => _.dicValue === val
      ).dicKey;
    },

    // 合同使用范本
    changeUseOfModelContractCode(name) {
      this.form.useOfModelContractCode = this.useOfModelContractOptions.find(
        _ => _.name === name
      ).code;
    },

    setOrgIdParams({ name, orgId }) {
      this.form.orgId = orgId;
      this.form.reportInOrgName = name;
      this.form.reportInOrgId = orgId;
      this.optionalParams = {
        ...this.optionalParams,
        reportInOrgId: orgId
      };
      this.setOrgId(orgId);
      this.setRangeList({ name, orgId });
      this.setAgreementSelectStatus(false);
      this.setSupplierData(this.supCode);
    },

    // 框架协议参照选择
    confirmSelect(val) {
      if (val.length) {
        this.initIsOverseas = this.form.isOverseas;
        this.initCurrencyCode = this.form.currencyCode;
        this.initCurrencyName = this.form.currencyName;
        this.initProtocalCode = this.form.protocalCode;
        this.initProtocalId = this.form.protocalId;
        this.initProtocalName = this.form.protocalName;
        this.initProtocalParams(val);
        this.setProtocalData(val);
        this.setIsOverseas(val[0].isOverseas);
        this.setCurrencyObj({
          code: val[0].currencyCode,
          name: val[0].currencyName
        });
        this.setDelectList(false);
        this.$nextTick(() => {
          if (this.getPurchaseListStatus) {
            this.agreementSelectTableList = val;
          }

          // 设置清单列表中的采购计划选择状态
          this.setAgreementSelectStatus(!!this.form.protocalCode);
        });
      }
    },

    // 选择协议重置是否海外采购、币种、兑换人民币汇率，对方联系人，对方手机
    initProtocalParams([protocalParams]) {
      if (protocalParams?.isShow !== null) {
        this.form.isShow = protocalParams.isShow;
      }
      // 是否海外采购
      // this.form.isOverseas =
      //   protocalParams.isOverseas || protocalParams.isOverseas === 0
      //     ? protocalParams.isOverseas
      //     : 3;
      // 币种
      // this.form.currencyName = protocalParams.currencyName || "人民币";
      // 兑换人民币汇率
      this.form.chExchangeRate = protocalParams.chExchangeRate
        ? protocalParams.chExchangeRate.toFixed(4)
        : this.form.chExchangeRate;
      // 对方联系人
      this.form.contractPerson =
        protocalParams.contractPerson || this.form.contractPerson;
      // 对方手机
      this.form.contractPersonTel =
        protocalParams.contractPersonTel || this.form.contractPersonTel;

      // 初始化币种
      this.beforeCurrencyName = protocalParams.currencyName || "人民币";
      this.beforeCurrencyCode = protocalParams.currencyCode || "1";
      this.form.currencyCode = protocalParams.currencyCode || "1";
    },

    // 提交表单验证
    handleSubmit() {
      return new Promise((resolve, reject) => {
        this.$refs["form"].validate(valid => {
          if (!valid) return reject("first");
          if (
            this.getInputRule(this.form.initTotalContractPriceIncludeTax) &&
            this.getInputRule(this.form.initTotalConractPriceExcludeTax)
          ) {
            resolve(this.form);
          } else {
            reject("third");
            return this.$showErrorMessage(
              "采购清单中含税单价不符合规范，请重新编辑"
            );
          }
        });
      });
    },

    // 多税率 change
    multiRateCodeChange(val) {
      this.$confirm("请注意，变更税率方式将会清空采购清单数量", "提示", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        customClass: "ccui-message-box-custom",
        closeOnClickModal: false
      })
        .then(() => {
          this.setMultiRateCode(val === 0 ? true : false);
          this.form.taxRatePercent = "";
          this.setTaxRate(0);
          // this.setMultiRateStatus(true);
        })
        .catch(error => {
          this.form.multiRateCode = this.form.multiRateCode === 1 ? 0 : 1;
        });
    },

    // 海外采购 change
    isOverseasChange(val) {
      this.setIsOverseas(val);
      if (val !== 3) {
        this.$refs["form"].clearValidate(["contractPersonTel"]);
      }
    },

    handleTrim(str) {
      this.form[str] = this.form[str].trim();
      // this.form[str] = this.form[str].replace(/(^\s*)|(\s*)$/g, "");
    },

    handleCurrencyChange(val) {
      const reg = /(^(\d{0,21})\.(\d{0,4})$)|(^\d{0,26}$)/;
      this.form[val] = Number(this.form[val]).toFixed(4);
      if (!reg.test(this.form[val])) {
        this.$showErrorMessage("请输入正确的税率");
        this.form[val] = "";
      }
    },

    getInputRule(val) {
      const reg = /(^(\d{0,11})\.(\d{0,8})$)|(^\d{0,20}$)/;
      return reg.test(val);
    },

    listProtocolinfoPage,
    ...mapActions([
      "setMultiRateCode", // 是否多税率
      "setTaxRate", // 税率默认为0
      "setOrgId", // 设置填报单位
      "setRangeList", // 范围列表
      "setSupplierData", // 供应商数据
      "setProtocalData", // 框架协议数据
      "setTaxRateObj", // 选择出税率数据（不为零）
      "setDelectList", // 是否清空了框架协议（清空框架协议同时清空协议、方案和计划引出的清单）
      "setMultiRateStatus", // 是否多税率好像没用
      "setShowDoubleTable", // 方案、计划下拉框是否可点
      "setAgreementSelectStatus", //设置清单列表中的采购计划选择状态???
      "setIsOverseas", // 是否海外采购
      "setProtocalCode", // 设置协议编号
      "setCurrencyObj" // 币种
    ])
  },
  computed: {
    ...mapGetters([
      "getContractPriceIncludeTax",
      "getContractPriceExcludeTax",
      "getEchoProtocalData",
      "getPurchaseListStatus",
      "getProtocalObj"
    ])
  },
  watch: {
    getEchoProtocalData: {
      immediate: true,
      handler(newVal) {
        this.agreementSelectTableList = newVal;
      }
    },
    getPurchaseListStatus(newVal) {
      if (!newVal) {
        this.form.isOverseas = this.initIsOverseas;
        this.form.currencyCode = this.initCurrencyCode;
        this.form.currencyName = this.initCurrencyName;
        this.form.protocalCode = this.initProtocalCode;
        this.form.protocalId = this.initProtocalId;
        this.form.protocalName = this.initProtocalName;
      }
    },
    "Enum.materialSourceList"(newVal) {
      if (newVal.length === 4) {
        newVal.pop();
        this.Enum.materialSourceList = newVal;
      }
    },
    "form.protocalCode": {
      immediate: true,
      handler(newVal) {
        this.beforeProtocalCode = newVal;
        this.setProtocalCode({ ...this.getProtocalObj, protocalCode: newVal });
      }
    },
    "form.protocalId": {
      immediate: true,
      handler(newVal) {
        this.beforeProtocalId = newVal;
        this.setProtocalCode({ ...this.getProtocalObj, protocalId: newVal });
      }
    },
    "form.protocalName": {
      immediate: true,
      handler(newVal) {
        this.beforeProtocalName = newVal;
        this.setProtocalCode({ ...this.getProtocalObj, protocalName: newVal });
      }
    },
    "form.isOverseas": {
      immediate: true,
      handler(newVal) {
        this.beforeIsOverseas = newVal;
        this.setProtocalCode({ ...this.getProtocalObj, isOverseas: newVal });
      }
    },
    "form.currencyName": {
      immediate: true,
      handler(newVal) {
        this.beforeCurrencyName = newVal;
        this.setProtocalCode({ ...this.getProtocalObj, currencyName: newVal });
      }
    },
    "form.currencyCode": {
      immediate: true,
      handler(newVal) {
        this.beforeCurrencyCode = newVal;
        this.setProtocalCode({ ...this.getProtocalObj, currencyCode: newVal });
      }
    },
    getProtocalObj(newVal) {
      this.form.isOverseas = newVal.isOverseas;
      this.form.currencyName = newVal.currencyName || "人民币";
      this.form.protocalCode = newVal.protocalCode;
      this.form.protocalId = newVal.protocalId;
      this.form.protocalName = newVal.protocalName;
      this.setProtocalCode(newVal);
    }
  }
};
</script>

<style scoped lang="scss">
.afterCurSettlePayAmtIncludeTax {
  position: absolute;
  top: -25px;
  left: 15px;
  color: #d8d8d8;
}
/deep/ .el-input {
  width: 260px;
}

/deep/ .el-button--single-number {
  width: 46px;
  margin-left: 10px;
  padding: 0 9px;
}
/deep/.ccui-pre-form-item {
  .el-form-item__label {
    line-height: 16px;
  }
}
.optionLeaf {
  padding-left: 20px;
}
</style>
